package com.atguigu.gmall.user.service.impl;

import com.atguigu.gmall.common.constant.RedisConst;
import com.atguigu.gmall.common.execption.GmallException;
import com.atguigu.gmall.common.result.ResultCodeEnum;
import com.atguigu.gmall.common.util.JSONs;
import com.atguigu.gmall.common.util.MD5;
import com.atguigu.gmall.user.entity.UserInfo;
import com.atguigu.gmall.user.mapper.UserInfoMapper;
import com.atguigu.gmall.user.service.UserInfoService;
import com.atguigu.gmall.user.vo.LoginResultVo;
import com.atguigu.gmall.user.vo.LoginVo;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author lyd
 * @description 针对表【user_info(用户表)】的数据库操作Service实现
 * @createDate 2023-08-29 16:42:38
 */
@Service
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo>
        implements UserInfoService {
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public LoginResultVo userLogin(LoginVo loginVo, String ip) {
        UserInfo userInfo = lambdaQuery()
                .eq(UserInfo::getLoginName, loginVo.getLoginName())
                .eq(UserInfo::getPasswd, MD5.encrypt(loginVo.getPasswd()))
                .one();
        //用户不存在，报错
        if (userInfo == null) {
            throw new GmallException(ResultCodeEnum.LOGIN_NAME_PWD_ERROR);
        }
        LoginResultVo result = new LoginResultVo();
        String token = UUID.randomUUID().toString().replaceAll("-", "");
        result.setToken(token);
        result.setNickName(userInfo.getNickName());
        result.setUserId(userInfo.getId());
        result.setName(userInfo.getName());

        //给UserInfo里面设置一个设备Id
        userInfo.setDeviceId(ip);

        redisTemplate.opsForValue().set(RedisConst.LOGIN_USER + token, JSONs.toJSONStr(userInfo), 7, TimeUnit.DAYS);
        return result;
    }

    /**
     * 退出登录
     * @param token
     */
    @Override
    public void logout(String token) {
        redisTemplate.delete(RedisConst.LOGIN_USER + token);
    }
}




